<?php
namespace App\Admin\Models;
use Common\BaseModel;
class User extends BaseModel
{
    public $res;
    public $redis_key = "user_";

    public function getSource()
    {
        return "f_users";
    }

    public function initialize()
    {
        parent::initialize();
    }

    public function userCount($data)
    {
        $where = "created_at >= '{$data['start_at']}' and created_at <= '{$data['end_at']}'";
        return $this::count($where);
    }

    public function level_name($level_id)
    {
        if ($level_id == 1) {
            return '合伙人';
        } elseif ($level_id = 2) {
            return '团队长';
        } else {
            return '高级团队长';
        }
    }

    public function details($where = '1=1', $columns = '*')
    {
        $data = [];
        $data = $this::findFirst(
            array(
                'conditions' => $where,
                "columns"    => $columns,
            )
        );
        return $data ? $data->toarray() : [];
    }

    public function userStatistics($st, $is_buyed)
    {
        $where['columns']    = "DATE_FORMAT(created_at, '%Y-%m-%d') AS MONTH , COUNT(*) AS counts";
        $where['conditions'] = "is_buyed = $is_buyed and created_at >= '{$st['start_at']}' AND created_at <= '{$st['end_at']}' ";
        $where['group']      = "MONTH";
        $where['order']      = "created_at asc";
        $list                = $this->find($where)->toarray();
        $result              = [];
        if (!empty($list)) {
            foreach ($list as $val) {
                $result[$val['MONTH']] = $val['counts'];
            }
        }
        return $result;
    }

    /**
     * 查询间接邀请粉丝数量（间接）
     */
    public function getIndirectFansCount($user_id, $path, $data = [])
    {
        $path       = $path . ',' . $user_id;
        $conditions = "path LIKE '{$path}%'";// AND referer_id <> $user_id
        if (isset($data['is_appuser'])) {
            if ($conditions) {
                $conditions .= " AND is_appuser={$data['is_appuser']}";
            } else {
                $conditions .= " is_appuser={$data['is_appuser']}";
            }
        }

        if (isset($data['updated_at'])) {
            $conditions .= " and updated_at >= '{$data['updated_at']}'";
        }

        if (isset($data['start_end_time']) && !empty($data['start_end_time'])) {
            if ($conditions) {
                $conditions .= " AND created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
            } else {
                $conditions = "created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
            }
        }


        if (isset($data['level_id'])) {
            if ($conditions) {
                $conditions .= " AND level_id in({$data['level_id']})";
            } else {
                $conditions = "level_id in({$data['level_id']})";
            }
        }


        if (isset($data['is_buyed'])) {
            if ($conditions) {
                $conditions .= " AND is_buyed={$data['is_buyed']}";
            } else {
                $conditions .= " is_buyed={$data['is_buyed']}";
            }
        }
        $count_array = $this:: count(array(
            $conditions,
            "column" => "id",
        ));
        return $count_array;
    }

    /**
     * 查询直接邀请粉丝数量（直邀）
     */
    public function getDirectFansCount($user_id, $data)
    {
        if (isset($data['start_end_time'])) {
            $conditions = "referer_id = {$user_id} AND created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
        } else {
            $conditions = "referer_id = {$user_id}";
        }
        if (isset($data['is_appuser']) && !empty($data['is_appuser'])) {
            if ($conditions) {
                $conditions .= " AND is_appuser={$data['is_appuser']}";
            } else {
                $conditions = "is_appuser={$data['is_appuser']}";
            }
        }
        if (isset($data['is_buyed'])) {
            if ($conditions) {
                $conditions .= " AND is_buyed={$data['is_buyed']}";
            } else {
                $conditions .= " is_buyed={$data['is_buyed']}";
            }
        }


        if (isset($data['level_id'])) {
            if ($conditions) {
                $conditions .= " AND level_id in({$data['level_id']})";
            } else {
                $conditions = "level_id in({$data['level_id']})";
            }
        }


        $count_array = $this:: count(array(
            $conditions,
            "column" => "id",
        ));
        return $count_array;
    }

    public function user_lists($params = [], $columns = '*')
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $size = 10;
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $condition = '1=1 ';

        if (isset($params['invite_code']) && !empty($params['invite_code'])) {
            $condition .= " and invite_code = '{$params['invite_code']}' or exclusive_code = '{$params['invite_code']}'";
        }
        if (isset($params['phone']) && !empty($params['phone'])) {
            $condition .= " and phone = '{$params['phone']}'";
        }
        if (isset($params['start_time']) && !empty($params['start_time'])) {
            $condition .= " and created_at >= '{$params['start_time']}'";
        }
        if (isset($params['end_time']) && !empty($params['end_time'])) {
            $condition .= " and created_at <= '{$params['end_time']}'";
        }
        $result['total'] = $this::count($condition);
        $result['list']  = $this::find(
            array(
                $condition,
                "order"   => 'id desc',
                'columns' => $columns,
                'limit'   => $size,
                'offset'  => $page
            ))->toarray();
        return $result;
    }

    //用户查找
    public function search_user($data = [])
    {
        $conditions = '';
        if (isset($data['invite_code']) && !empty($data['invite_code'])) {
            $conditions = "invite_code ='{$data['invite_code']}' or exclusive_code ='{$data['invite_code']}'";
        }
        if (isset($data['phone']) && !empty($data['phone'])) {
            if ($conditions) {
                $conditions .= " AND phone='{$data['phone']}'";
            } else {
                $conditions = "phone='{$data['phone']}'";
            }
        }
        if (isset($data['alipay_account']) && !empty($data['alipay_account'])) {
            if ($conditions) {
                $conditions .= " AND alipay_account='{$data['alipay_account']}'";
            } else {
                $conditions = "alipay_account='{$data['alipay_account']}'";
            }
        }
        if (isset($data['alipay_name']) && !empty($data['alipay_name'])) {
            if ($conditions) {
                $conditions .= " AND real_name='{$data['alipay_name']}'";
            } else {
                $conditions = "real_name='{$data['alipay_name']}'";
            }
        }
        $get_list = $this->find(array(
            $conditions,
            'columns' => 'id',
        ))->toarray();
        $ids_arr  = array_column($get_list, 'id');
        return implode(',', $ids_arr);
    }


    //我的直推粉丝
    public function my_direct_fans($params = [], $method = 'find')
    {
        $page = intval($params['page']);
        $size = intval($params['limit']);
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $userInfo = $this->findFirstById($params['user_id']);
        $path     = $userInfo->path . ',' . $userInfo->referer_id . ',' . $userInfo->id;

        switch ($params['type']) {
            case 1:
                $conditions = "referer_id={$params['user_id']}";
                break;
            case 2:
                $conditions = "path = '$path'";
                break;
            case 3:
                $conditions = "path like '$path%' and path != '$path'";
                break;
            default:
                $conditions = "referer_id={$params['user_id']}";
        }
        if ($method == 'find') {
            $cate_list = $this::find(
                array(
                    $conditions,
                    "order"  => 'id desc',
                    'limit'  => $size,
                    'offset' => $page
                )
            )->toarray();
        } else {
            $cate_list = $this->count(array(
                $conditions,
            ));
        }
        return $cate_list;
    }


    //原生查询
    public function my_direct_fans_sql($params = [], $method = 'find')
    {
        $order = 'id desc';
        if (isset($params['order_by']) && !empty($params['order_by']) && isset($params['sort']) && !empty($params['sort'])) {
            $order = "{$params['order_by']} {$params['sort']}";
        }


        $page = intval($params['page']);
        $size = intval($params['limit']);
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $userInfo = $this->findFirstById($params['user_id']);
        if ($userInfo->path) {
            $path = $userInfo->path . ',' . $userInfo->referer_id . ',' . $userInfo->id;
        } else {
            $path = $userInfo->referer_id . ',' . $userInfo->id;

        }

        switch ($params['type']) {
            case 1:
                $conditions = "referer_id={$params['user_id']}";
                break;
            case 2:
                $conditions = "path = '$path'";
                break;
            case 3:
                $conditions = "path like '$path%' and path != '$path'";
                break;
            default:
                $conditions = "referer_id={$params['user_id']}";
        }

        $phql       = <<<ENT
        select u.*,order_count,yugu_money from `f_users` as u
        left join
        (select COUNT(user_id) as order_count,user_id from `w_union_order` group by user_id) as o on o.user_id=u.id
        left join
        (select SUM(money) as yugu_money,user_id from `w_order_commissions` where order_status in (2,4,6) group by user_id) as oc on oc.user_id=u.id
        where $conditions
        order by $order
        limit $page,$size
ENT;
        $row = $this->di->get('dbMaster')->fetchAll($phql);
        return $row;
    }


    //我的直邀ids
    public function referer_ids($user_id)
    {
        $condition = "referer_id={$user_id}";
        $user_ids  = $this->find(array(
            $condition,
            'columns' => 'id',
        ))->toarray();
        if ($user_ids) {
            $ids = implode(',', array_column($user_ids, 'id'));
            return $ids;
        } else {
            return '-1';
        }
    }


    //我的间接
    public function indirect_ids($user_id)
    {
//        $referer_ids = $this->referer_ids($user_id);
//        $condition = "referer_id in({$referer_ids})";

        $user_info = $this->findFirstById($user_id);
        if ($user_info->path) {
            $path = $user_info->path . ',' . $user_info->referer_id . ',' . $user_info->id;
        } else {
            $path = $user_info->referer_id . ',' . $user_info->id;
        }
        $condition = "path = '$path'";
        $users_ids = $this->find(array(
            $condition,
            'columns' => 'id',
        ))->toarray();
        if ($users_ids) {
            $ids = implode(',', array_column($users_ids, 'id'));
            return $ids;
        } else {
            return '-1';
        }
    }


    //间接以后
    public function indirect_indirect_ids($user_id)
    {
        $user_info = $this->findFirstById($user_id);
        if (!$user_info) {
            return -1;
        }
        if ($user_info->path) {
            $path = $user_info->path . ',' . $user_info->referer_id . ',' . $user_info->id;
        } else {
            $path = $user_info->referer_id . ',' . $user_info->id;
        }
        //$conditions = "path like '{$path}%'";
        $conditions = "path like '$path%' and path != '$path'";
        $paths_ids  = $this->find(array(
            $conditions,
            'columns' => 'id',
        ))->toarray();
        if (!$paths_ids) {
            return -1;
        }
        $ids = implode(',', array_column($paths_ids, 'id'));
        return $ids;
    }

    public function smsUserList($params)
    {
        $page = intval($params['page']);
        $size = isset($params['limit']) ? intval($params['limit']) : 10;
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $order = 'id asc';
        if (isset($params['order']) && !empty($params['order'])) {
            $order = $params['order'];
        }
        $conditions = ' 1=1 ';
        //最近消费时间开始
        if (isset($params['order_create_time_beg']) && !empty($params['order_create_time_beg'])) {
            $conditions .= " and b.order_create_time >= '{$params['order_create_time_beg']}'";
        }
        //最近消费时间结束
        if (isset($params['order_create_time_end']) && !empty($params['order_create_time_end'])) {
            $conditions .= " and b.order_create_time <= '{$params['order_create_time_end']}'";
        }
        //订单数
        if (isset($params['order_count_beg']) && !empty($params['order_count_beg'])) {
            $conditions .= " and c.order_count >= {$params['order_count_beg']}";
        }
        //订单数结束
        if (isset($params['order_count_end']) && !empty($params['order_count_end'])) {
            $conditions .= " and c.order_count <= {$params['order_count_end']}";
        }
        //累计消费开始
        if (isset($params['pay_money_beg']) && !empty($params['pay_money_beg'])) {
            $conditions .= " and d.pay_money >= {$params['pay_money_beg']}";
        }
        //累计消费结束
        if (isset($params['pay_money_end']) && !empty($params['pay_money_end'])) {
            $conditions .= " and d.pay_money <= {$params['pay_money_end']}";
        }
        //均价开始
        if (isset($params['pay_money_avg_beg']) && !empty($params['pay_money_avg_beg'])) {
            $conditions .= " and e.pay_money_avg >= {$params['pay_money_avg_beg']}";
        }
        //均价结束
        if (isset($params['pay_money_avg_end']) && !empty($params['pay_money_avg_end'])) {
            $conditions .= " and e.pay_money_avg <= {$params['pay_money_avg_end']}";
        }
        //等级1,2,3,4,5
        if (isset($params['level_id']) && !empty($params['level_id'])) {
            if ($params['level_id'] == 2) {
                $conditions .= " and f.level_id = 2 and f.svip_forever = 0 and f.svip_count_time > 0";
            } elseif ($params['level_id'] == 3) {
                $conditions .= " and f.level_id = 2 and f.svip_forever = 1";
            } else {
                if($params['level_id'] >= 4){
                    $params['level_id'] -= 1;
                }
                $conditions .= " and f.level_id = {$params['level_id']}";
            }
        }
        $phql            ="
        SELECT f.svip_forever,f.svip_count_time,a.id,a.nickname,a.phone,f.`level_id`,d.pay_money,c.order_count,e.pay_money_avg,b.order_create_time FROM f_users AS a 
LEFT JOIN (SELECT user_id,order_create_time FROM `w_union_order` AS b WHERE NOT EXISTS(SELECT 1 FROM `w_union_order` WHERE user_id= b.user_id
AND b.order_create_time < order_create_time ) GROUP BY user_id) AS b ON b.user_id = a.id  
LEFT JOIN (SELECT COUNT(id) AS order_count,user_id FROM `w_union_order` WHERE order_status IN (2,4,6) GROUP BY user_id) AS c ON c.user_id = a.id 
LEFT JOIN (SELECT SUM(pay_money) AS pay_money,user_id FROM `w_union_order` WHERE order_status IN (2,4,6) GROUP BY user_id) AS d ON d.user_id = a.id 
LEFT JOIN (SELECT AVG(pay_money) AS pay_money_avg,user_id FROM `w_union_order` WHERE order_status IN (2,4,6) GROUP BY user_id) AS e ON e.user_id = a.id 
LEFT JOIN www_extend AS f ON f.`user_id` = a.id 
        where $conditions
        order by $order
        limit $page,$size";
        $connection      = $this->di->get('db');
        $result['items'] = $connection->fetchAll($phql);

        $phql = "SELECT count(a.id) as count FROM f_users AS a 
LEFT JOIN (SELECT user_id,order_create_time FROM `w_union_order` AS b WHERE NOT EXISTS(SELECT 1 FROM `w_union_order` WHERE user_id= b.user_id
AND b.order_create_time<order_create_time ) GROUP BY user_id) AS b ON b.user_id = a.id 
LEFT JOIN (SELECT COUNT(id) AS order_count,user_id FROM `w_union_order` WHERE order_status IN (2,4,6) GROUP BY user_id) AS c ON c.user_id = a.id 
LEFT JOIN (SELECT SUM(pay_money) AS pay_money,user_id FROM `w_union_order` WHERE order_status IN (2,4,6) GROUP BY user_id) AS d ON d.user_id = a.id 
LEFT JOIN (SELECT AVG(pay_money) AS pay_money_avg,user_id FROM `w_union_order` WHERE order_status IN (2,4,6) GROUP BY user_id) AS e ON e.user_id = a.id 
LEFT JOIN www_extend AS f ON f.`user_id` = a.id 
        where $conditions";

        $count           = $connection->fetchOne($phql);
        $result['total'] = $count['count'] ? $count['count'] : 0;
        return $result;
    }
}
